package model

import (
	"app/internal/pkg/config"
	"log"

	sqlite_go "github.com/glebarez/sqlite" // sqlite driver without cgo
	mysql "gorm.io/driver/mysql"           // mysql driver
	sqlite "gorm.io/driver/sqlite"         // sqlite driver
	"gorm.io/gorm"
)

var db *gorm.DB

// init database connection and migrate database
func InitDB() {
	var err error
	switch config.Driver {
	case "sqlite":
		db, err = gorm.Open(sqlite.Open(config.DataSource), &gorm.Config{})
	case "sqlite_go":
		db, err = gorm.Open(sqlite_go.Open(config.DataSource), &gorm.Config{})
	case "mysql":
		db, err = gorm.Open(mysql.Open(config.DataSource), &gorm.Config{})
	default:
		log.Fatal("unsupported database driver: ", config.Driver)
	}

	// 检查数据库连接是否成功
	if err != nil {
		log.Fatal("failed to connect database: ", err)
	}

	// 自动迁移用户表结构
	if err := db.AutoMigrate(&User{}); err != nil {
		log.Fatal("failed to migrate database: ", err)
	}
}

func CloseDB() error {
	if db == nil {
		return nil
	}
	sqlDB, err := db.DB()
	if err != nil {
		return err
	}
	return sqlDB.Close()
}
